package com.fy56.platform.logistics.restful.api.controller.wx;


import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.MiniProgram;
import com.fy56.platform.logistics.model.PayOrder;
import com.fy56.platform.logistics.model.Vip;
import com.fy56.platform.logistics.service.web.IMiniProgramService;
import com.fy56.platform.logistics.service.wx.IPayOrderService;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.IVipService;
import com.fy56.platform.logistics.utils.StringUtil;
import com.wordnik.swagger.annotations.Api;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 支付订单Controller
 *
 * @author
 * @version 2019-01-06
 */
@Api(value = "PayOrder", description = "支付统一订单", produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping("/payOrder")
public class PayOrderController {

    private static Logger log = Logger.getLogger(PayOrderController.class);

    @Autowired
    private ICompanyInfoService iCompanyInfoService;
    @Autowired
    private IVipService iVipService;
    @Autowired
    private IMiniProgramService iMiniProgramService;
    @Autowired
    private IPayOrderService iPayOrderService;

    /**
     * 统一下单接口功能
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/savePayOrder
     * @param data = {orderNo:"XCXORDER-1001-1",code:"M6120",openId:"123456",mobile:"13664610217",money:"1.1"}
     */
    @RequestMapping(value = "/savePayOrder", method = RequestMethod.POST)
    public ResponseEntity savePayOrder(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder,"openId-orderBillId-mobile-code-orderNo-money");
                Object remark = parameter.get("remark");
                if(remark != null){
                    payOrder.setRemark(remark.toString());
                }
                //2 调用统一下单ServiceImp发功能
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.insertSelective(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-savePayOrder，下单savePayOrder功能异常：", ex);
            result = new ResultModel(101, "下单savePayOrder功能异常。",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取支付订单签名数据信息
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/getPayOrderSignCode
     * @param data {orderId:"XCXORDER-1001-2"}
     * @return
     */
    @RequestMapping(value = "/getPayOrderSignCode", method = RequestMethod.POST)
    public ResponseEntity getPayOrderSignCode(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = "";
                Object orderId = parameter.get("orderId");
                if(orderId != null && StringUtil.isNotEmpty(orderId.toString())){
                    payOrder.setOrderId(orderId.toString());
                }else{
                    orderId += "orderId参数有误 ";
                }
                //2 调用统一下单ServiceImp发功能
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.getPayOrderSignCodeService(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-getPayOrderSignCode，获取支付订单签名数据信息功能异常：", ex);
            result = new ResultModel(101, "获取支付订单签名数据信息功能异常。",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 关闭待支付订单 - 未使用
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/closePayOrder
     * @param data {code:"M6120",orderNo:"XCXORDER-1001-1"}
     * @return
     */
    @RequestMapping(value = "/closePayOrder", method = RequestMethod.POST)
    public ResponseEntity closePayOrder(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (StringUtil.isNotEmpty(data)){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();


                //1 验证客户端传入调用参数[code,orderNo]
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder,"code-orderNo");
                // 2 查询统一下单 根据单号
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.updateClosePayOrder(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-closePayOrder，根据交易单号关闭订单功能异常：", ex);
            result = new ResultModel(101, "根据交易单号关闭订单功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 更新订单支付状态 - 状态更新了 --- 但是未使用该接口
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/updateOrderPayState
     * @param data {mobile:"15004526246",orderNo:"XCXORDER-1001-1",payState:1,payResultMsg:"已经支付了, 支付了2 QQ币"}
     * @return
     */
    @RequestMapping(value = "/updateOrderPayState", method = RequestMethod.POST)
    public ResponseEntity updateOrderPayState(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder, "orderBillId-orderNo-code-mobile-payState");
                Object payState = parameter.get("payState");
                if(payState != null){
                    payOrder.setPayState(Integer.parseInt(payState.toString()));
                }
                Object payResultMsg = parameter.get("payResultMsg");
                if(payResultMsg != null){
                    payOrder.setPayResultMsg(payResultMsg.toString());
                }
                // 2 查询统一下单 根据单号
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.updateOrderPayStateService(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-updateOrderPayState，根据交易单号,更新订单支付状态功能异常：", ex);
            result = new ResultModel(101, "根据交易单号,更新订单支付状态功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 发起退款申请
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/returnPayOrderMoney
     * @param data {mobile:"15004526246",payState:1,payResultMsg:"已经支付了, 支付了2 QQ币"}
     * @return
     */
    @RequestMapping(value = "/returnPayOrderMoney", method = RequestMethod.POST)
    public ResponseEntity returnPayOrderMoney(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();
                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder, "code-orderId-orderBillId");
                Object refundApplyReason = parameter.get("refundApplyReason");
                if(refundApplyReason != null){
                    payOrder.setRefundApplyReason(refundApplyReason.toString());
                }
                // 2 发起退款申请
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.returnPayOrderMoneyService(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-returnPayOrderMoney，支付订单发起退款申请功能异常：", ex);
            result = new ResultModel(101, "支付订单发起退款申请功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 删除支付订单 - 未使用
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/deletePayOrder
     * @param data {orderNo:"XCXORDER-1001-2"}
     * @return
     */
    @RequestMapping(value = "/deletePayOrder", method = RequestMethod.POST)
    public ResponseEntity deletePayOrder(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder,"orderNo");
                // 2 根据订单编号与用户信息，删除支付订单信息
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.deletePayOrderService(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-deletePayOrder，删除支付订单功能异常：", ex);
            result = new ResultModel(101, "删除支付订单功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /***
     * 根据按交易单号查询交易明细 - 未使用
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/getPayOrder
     * @param data {code:"M6120",orderNo:"XCXORDER-1001-2"}
     * @return
     */
    @RequestMapping(value = "/getPayOrder", method = RequestMethod.POST)
    public ResponseEntity getPayOrder(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder,"code-orderNo");
                // 2 查询统一下单 根据单号
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    PayOrder resultPayOrder = iPayOrderService.get(payOrder);
                    if(resultPayOrder != null){
                        result = new ResultModel(100, "查询支付订单成功", resultPayOrder);
                    }else{
                        result = new ResultModel(101,  "支付订单查询失败,不存在的订单编号:" + parameter.get("orderNo"),null);
                    }
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-getPayOrder，根据交易单号查询订单功能异常：", ex);
            result = new ResultModel(101, "根据交易单号查询订单功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /***
     * 根据用户信息，查询用户支付订单列表 - 未使用
     *
     * http://localhost:8080/logistics-restful-api-test/payOrder/findPayOrderList
     * @param data {mobile:"15004526246",orderNo:"",closeState:1,startCreateTime:"2019-01-17 00:00:00",endCreateTime:"2019-01-17 23:59:59",startPayTime:"",endPayTime:""}
     * @return
     */
    @RequestMapping(value = "/findPayOrderList", method = RequestMethod.POST)
    public ResponseEntity findPayOrderList(@RequestParam String data) {
        ResultModel result = null;
        try{
            if (data !=null && data.length() != 0){
                Map<String,Object> parameter = JSON.parseObject(data);
                PayOrder payOrder = new PayOrder();

                //1 验证客户端传入调用参数
                String paramErrorMsg = validataPayOrderParams(parameter, payOrder,"mobile");
                Object orderNo = parameter.get("orderNo");
                if(orderNo != null){
                    payOrder.setOrderNo(orderNo.toString());
                }
                Object payState = parameter.get("payState");
                if(payState != null){
                    payOrder.setPayState(Integer.parseInt(payState.toString()));
                }
                Object closeState = parameter.get("closeState");
                if(closeState != null){
                    payOrder.setCloseState(Integer.parseInt(closeState.toString()));
                }
                Object startCreateTime = parameter.get("startCreateTime");
                if(startCreateTime != null){
                    payOrder.setStartCreateTime(getParamterDateValue(startCreateTime.toString(),null));
                }
                Object endCreateTime = parameter.get("endCreateTime");
                if(startCreateTime != null){
                    payOrder.setEndCreateTime(getParamterDateValue(endCreateTime.toString(),null));
                }
                Object startPayTime = parameter.get("startPayTime");
                if(startPayTime != null){
                    payOrder.setStartPayTime(getParamterDateValue(startPayTime.toString(),null));
                }
                Object endPayTime = parameter.get("endPayTime");
                if(endPayTime != null){
                    payOrder.setEndPayTime(getParamterDateValue(endPayTime.toString(),null));
                }
                // 2 查询支付订单列表
                if (StringUtil.isEmpty(paramErrorMsg)) {
                    result = iPayOrderService.findPayOrderListService(payOrder);
                }else{
                    result = new ResultModel(101, paramErrorMsg,null);
                }
            }
        }catch (Exception ex){
            log.error("PayOrder支付订单-findPayOrderList，查询用户支付订单列表功能异常：", ex);
            result = new ResultModel(101, "查询用户支付订单列表功能异常",null);
            ex.printStackTrace();
        }
        return  new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 验证方法传入参数是否合法
     *
     * @param parameter
     * @param payOrder
     * @return
     */
    public String validataPayOrderParams(Map<String, Object> parameter, PayOrder payOrder, String validateParams){
        String resultVaildataMsg = "";

        // 0 验证支付订单 订单编码
        if(validateParams.indexOf("openId") > -1){
            Object openId = parameter.get("openId");
            if(openId != null && StringUtil.isNotEmpty(openId.toString())){
                payOrder.setOpenId(openId.toString());
            }else{
                resultVaildataMsg += "openId参数有误 ";
            }
        }
        if(validateParams.indexOf("orderId") > -1){
            Object orderId = parameter.get("orderId");
            if(orderId != null && StringUtil.isNotEmpty(orderId.toString())){
                payOrder.setOrderId(orderId.toString());
            }else{
                resultVaildataMsg += "orderId参数有误 ";
            }
        }
        // 支付类型
        if(validateParams.indexOf("payType") > -1){
            Object payType = parameter.get("payType");
            if(payType != null && StringUtil.isNotEmpty(payType.toString())){
                String tempValue = "运费".equals(payType.toString())?"YUNFEI":"CHAJIA";
                payOrder.setGeneratorOrderType(tempValue);
            }else{
                resultVaildataMsg += "payType参数有误 ";
            }
        }
        // 1 验证支付订单 订单编码
        if(validateParams.indexOf("orderNo") > -1){
            Object orderNo = parameter.get("orderNo");
            if(orderNo != null && StringUtil.isNotEmpty(orderNo.toString())){
                /** 返回null说明数据库中存在支付订单数据，返回编号则说明没有当前编号数据 **/
                String payOrderNo = iPayOrderService.getPayOrderNotByParamsService(orderNo.toString());
                if(StringUtil.isNotEmpty(payOrderNo)) {
                    if(payOrderNo.indexOf("YUNFEI") > -1) {
                        payOrder.setGeneratorOrderType("YUNFEI");
                    }
                    if(payOrderNo.indexOf("CHAJIA") > -1) {
                        payOrder.setGeneratorOrderType("CHAJIA");
                    }
                    payOrder.setOrderId(orderNo.toString());
                    payOrder.setOrderNo(payOrderNo);
                }else{
                    payOrder.setOrderId(orderNo.toString());
                }
                /* 不验证订单是否存在
                else{
                    resultVaildataMsg += orderNo + "支付订单已存在 ";
                }*/

            }else{
                resultVaildataMsg += "orderNo参数有误 ";
            }
        }
        // 回退支付状态到F6
        if(validateParams.indexOf("orderBillId") > -1){
            Object orderBillId = parameter.get("orderBillId");
            if(orderBillId != null && StringUtil.isNotEmpty(orderBillId.toString())){
                payOrder.setOrderBillId(orderBillId.toString());
            }else{
                resultVaildataMsg += "orderBillId参数有误 ";
            }
        }
        // 2 验证金融平台公司编码 对应公司是否存在
        if(validateParams.indexOf("code") > -1){
            Object code = parameter.get("code");
            if(code != null && StringUtil.isNotEmpty(code.toString())){
                // 获取code对应关联的小程序设置信息
                MiniProgram miniProgram = iMiniProgramService.selectByCode(code.toString());
                if(miniProgram != null && StringUtil.isNotEmpty(miniProgram.getTradingcenterUrl()) && StringUtil.isNotEmpty(miniProgram.getTradingcenterMchKey())){
                    payOrder.setAppId(miniProgram.getAppid());
                    payOrder.setMiniProgram(miniProgram);
                }else{
                    resultVaildataMsg += "code对应小程序与支付信息未设置 ";
                }
                // 获取code 对应关联的company信息
                Company company =  iCompanyInfoService.getCompanyByCode(code.toString());
                if(company != null){
                    payOrder.setCompany(company);
                }else{
                    resultVaildataMsg += "code无对应公司信息 ";
                }
                payOrder.setCode(code.toString());
            }else{
                resultVaildataMsg += "code参数有误 ";
            }
        }
        // 3 验证用户信息是否存在
        if (validateParams.indexOf("mobile") > -1){
            Object mobile = parameter.get("mobile");
            if(mobile != null && StringUtil.isNotEmpty(mobile.toString())){
                Vip vipMember = iVipService.selectVipOpenidByMobile(mobile.toString());
                if(vipMember != null){
                    payOrder.setVipMemberId(vipMember.getId()+"");
                    payOrder.setMobile(vipMember.getMobile());
                    payOrder.setVip(vipMember);
                }else{
                    resultVaildataMsg += (mobile.toString() +",用户不存在 ");
                }
                payOrder.setMobile(mobile.toString());
            }else{
                resultVaildataMsg += "mobile参数有误 ";
            }
        }
        // 5 money
        if (validateParams.indexOf("money") > -1) {
            Object money = parameter.get("money");
            if (money != null && StringUtil.isNotEmpty(money.toString())) {
                payOrder.setMoney(Double.parseDouble(money.toString()));
            } else {
                resultVaildataMsg += "money参数有误 ";
            }
        }
        // 6 goodsDescribe 消费项目名称
        if(validateParams.indexOf("goodsDescribe") > -1){
            Object goodsDescribe = parameter.get("goodsDescribe");
            if(goodsDescribe != null && StringUtil.isNotEmpty(goodsDescribe.toString())){
                payOrder.setGoodsDescribe(goodsDescribe.toString());
            }else{
                resultVaildataMsg += "goodsDescribe参数有误 ";
            }
        }
        // 7 payState 支付状态
        if(validateParams.indexOf("payState") > -1){
            Object payState = parameter.get("payState");
            if(payState != null && StringUtil.isNotEmpty(payState.toString())){
                payOrder.setPayState(Integer.parseInt(payState.toString()));
            }else{
                resultVaildataMsg += "payState参数有误 ";
            }
        }
        return resultVaildataMsg;
    }

    /***
     * 根据给定格式将日期转换为日期类型
     *
     * @param dateValue
     * @param format
     * @return
     */
    private Date getParamterDateValue(String dateValue, String format){
        Date result = null;
        String defaultFormat = "yyyy-MM-dd HH:mm:ss";
        try{
            if(StringUtil.isEmpty(format)){
                format = defaultFormat;
            }
            result = new SimpleDateFormat(format).parse(dateValue);
        }catch (Exception ex){
            log.error("日期数据格式化类型错误:", ex);
        }
        return result;
    }


}
